<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>基本资料</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <script src="../lib/jquery-3.4.1/jquery-3.4.1.min.js"></script>
    <script src="../lib/layui-v2.6.3/layui.js"></script>
</head>
<body class="layui-layout-body">

<div class="layui-container" style="margin-top: 30px;">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-field-box" style="padding: 20px;">
                <!-- 用户头像 -->
                <div class="layui-row layui-col-space20">
                    <div class="layui-col-md3 text-center">
                        <img id="avatar" src="" alt="头像" class="layui-circle" width="120" height="120">
                        <p style="margin-top: 10px; font-size: 14px;">当前头像</p>
                    </div>

                    <div class="layui-col-md9">
                        <table class="layui-table">
                            <tbody>
                            <tr><td>用户名</td><td id="username"></td></tr>
                            <tr><td>真实姓名</td><td id="realName"></td></tr>
                            <tr><td>手机号</td><td id="mobile"></td></tr>
                            <tr><td>邮箱</td><td id="email"></td></tr>
                            <tr><td>性别</td><td id="gender"></td></tr>
                            <tr><td>身份证号</td><td id="idCard"></td></tr>
                            <tr><td>最后更新时间</td><td id="lastUpdateTime"></td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="layui-btn-container" style="text-align: center; margin-top: 20px;">
                <button class="layui-btn" id="editProfileBtn"><i class="layui-icon layui-icon-edit"></i> 编辑资料</button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑资料弹窗 -->
<script type="text/html" id="editFormTpl">
    <form class="layui-form" id="editProfileForm" style="padding: 20px;">
        <div class="layui-form-item">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-block">
                <input type="text" name="realName" id="edit-realName" lay-verify="required" placeholder="请输入真实姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号</label>
            <div class="layui-input-block">
                <input type="text" name="mobile" id="edit-mobile" lay-verify="phone|required" placeholder="请输入手机号码" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">身份证号</label>
            <div class="layui-input-block">
                <input type="text" name="idCard" id="edit-idCard" lay-verify="required" placeholder="请输入身份证号码" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="email" id="edit-email" lay-verify="email|required" placeholder="请输入邮箱地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="1" title="男" id="gender-male">
                <input type="radio" name="gender" value="2" title="女" id="gender-female">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">头像图片</label>
            <div class="layui-input-block">
                <input type="file" id="avatarUpload" accept="image/*">
                <input type="hidden" name="faceImageUrl" id="faceImageUrl">
                <img id="avatarPreview" class="layui-circle" style="display:none; margin-top: 8px;" width="120" height="120">
                <div class="layui-form-mid layui-word-aux">请选择要上传的头像图片（支持 jpg/png 格式）</div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveProfile">保存更改</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>


    </form>
</script>

<script>
    layui.use(['layer', 'form'], function () {
        const $ = layui.$;
        const layer = layui.layer;
        const form = layui.form;

        const userStr = localStorage.getItem('user');
        const user = JSON.parse(userStr);
        const userId = user.user.userId;

        $.ajaxSetup({
            beforeSend: function(xhr) {
                const data = JSON.parse(localStorage.getItem('user'));
                if (data && data.token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                }
            }
        });

        // 获取用户资料
        function fetchUserProfile() {
            $.ajax({
                url: '/user/profile',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ userId: userId }),
                success: function (res) {
                    if (!res || res.code !== 0) {
                        layer.msg("获取用户信息失败", { icon: 2 });
                        return;
                    }

                    const userData = res.data;

                    $('#username').text(userData.username || '');
                    $('#realName').text(userData.realName || '未填写');
                    $('#mobile').text(userData.mobile || '');
                    $('#email').text(userData.email || '');
                    $('#idCard').text(userData.idCard || '');
                    $('#gender').text(userData.gender === 1 ? '男' : userData.gender === 2 ? '女' : '未知');
                    $('#avatar').attr('src', userData.faceImageUrl || 'https://via.placeholder.com/120');
                    $('#lastUpdateTime').text(userData.updateTime || '--');
                },
                error: function (xhr, status, error) {
                    layer.msg('请求失败，请稍后再试', { icon: 2 });
                }
            });
        }

        // 初次加载
        fetchUserProfile();
        // 绑定头像上传事件

        $(document).on('click', '#avatar', function () {
            const src = $(this).attr('src');
            if (src && src !== 'https://via.placeholder.com/120') {
                layer.photos({
                    photos: {
                        "title": "当前头像",
                        "data": [{ src: src }]
                    }
                });
            }
        });

        // 编辑按钮点击事件
        $('#editProfileBtn').on('click', function () {
            // 再次请求用户数据以填充表单
            $.ajax({
                url: '/user/profile',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ userId: userId }),
                success: function (res) {
                    if (!res || res.code !== 0) {
                        layer.msg("获取用户信息失败", { icon: 2 });
                        return;
                    }

                    const userData = res.data;

                    // 弹出层
                    layer.open({
                        type: 1,
                        title: '编辑个人资料',
                        area: ['500px', '400px'],
                        content: $('#editFormTpl').html(),
                        success: function (layero, index) {
                            // 填充表单
                            $('#edit-realName').val(userData.realName || '');
                            $('#edit-mobile').val(userData.mobile || '');
                            $('#edit-email').val(userData.email || '');
                            $('#edit-idCard').val(userData.idCard || '');
                            if (userData.gender === 1) {
                                $('#gender-male').prop('checked', true);
                            } else if (userData.gender === 2) {
                                $('#gender-female').prop('checked', true);
                            }

                            form.render(); // 渲染表单
                            $('#avatarUpload').off('change').on('change', function () {
                                const file = this.files[0];
                                if (!file) return;

                                const formData = new FormData();
                                formData.append('file', file);

                                layer.msg('图片上传中...', { icon: 16, shade: 0.2, time: 0 });

                                $.ajax({
                                    url: '/oss/upload',
                                    type: 'POST',
                                    data: formData,
                                    processData: false,
                                    contentType: false,
                                    success: function (res) {
                                        layer.closeAll('loading');
                                        if (res.code === 0) {
                                            $('#avatarPreview').attr('src', res.data).show();
                                            $('#faceImageUrl').val(res.data);
                                            layer.msg('图片上传成功');
                                        } else {
                                            layer.msg('图片上传失败: ' + res.message, { icon: 2 });
                                        }
                                    },
                                    error: function () {
                                        layer.closeAll('loading');
                                        layer.msg('图片上传失败', { icon: 2 });
                                    }
                                });
                            });
                            // 表单提交
                            form.on('submit(saveProfile)', function (data) {
                                const formData = data.field;
                                formData.userId = userId;
                                formData.realName = $('#edit-realName').val(); // 手动赋值
                                formData.idCard = $('#edit-idCard').val();
                                formData.faceImageUrl = $('#faceImageUrl').val(); // 添加头像URL



                                $.ajax({
                                    url: '/user/changeProfile',
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(formData),
                                    success: function (response) {
                                        if (response.code === 0) {
                                            // 获取当前时间并格式化为 YYYY-MM-DD HH:mm:ss
                                            const now = new Date();
                                            const year = now.getFullYear();
                                            const month = String(now.getMonth() + 1).padStart(2, '0');
                                            const day = String(now.getDate()).padStart(2, '0');
                                            const hours = String(now.getHours()).padStart(2, '0');
                                            const minutes = String(now.getMinutes()).padStart(2, '0');
                                            const seconds = String(now.getSeconds()).padStart(2, '0');
                                            const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

                                            // 更新页面上的“最后更新时间”
                                            $('#lastUpdateTime').text(currentTime);
                                            $('#avatar').attr('src', formData.faceImageUrl || 'https://via.placeholder.com/120');


                                            layer.msg('资料更新成功', { icon: 1 });
                                            layer.close(index);
                                        } else {
                                            layer.msg(response.message || '更新失败', { icon: 2 });
                                        }
                                    },
                                    error: function () {
                                        layer.msg('网络错误，请重试', { icon: 5 });
                                    }
                                });

                                return false;
                            });
                        }
                    });
                },
                error: function () {
                    layer.msg('获取用户信息失败', { icon: 2 });
                }
            });
        });
    });
</script>

</body>
</html>
